package com.farm.doc.server.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.farm.authority.domain.User;
import com.farm.core.auth.domain.LoginUser;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBSort;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.time.TimeTool;
import com.farm.doc.dao.FarmDocDaoInter;
import com.farm.doc.dao.FarmDocenjoyDaoInter;
import com.farm.doc.dao.FarmDocfileDaoInter;
import com.farm.doc.dao.FarmDocruninfoDaoInter;
import com.farm.doc.dao.FarmDocruninfoDetailDaoInter;
import com.farm.doc.dao.FarmDoctextDaoInter;
import com.farm.doc.dao.FarmDoctypeDaoInter;
import com.farm.doc.dao.FarmRfDoctextfileDaoInter;
import com.farm.doc.dao.FarmRfDoctypeDaoInter;
import com.farm.doc.dao.FarmtopDaoInter;
import com.farm.doc.domain.Doc;
import com.farm.doc.domain.FarmDocfile;
import com.farm.doc.domain.FarmDocruninfo;
import com.farm.doc.domain.FarmDoctext;
import com.farm.doc.domain.FarmDoctype;
import com.farm.doc.domain.FarmRfDoctextfile;
import com.farm.doc.domain.FarmRfDoctype;
import com.farm.doc.domain.ex.DocEntire;
import com.farm.doc.exception.CanNoDeleteException;
import com.farm.doc.exception.CanNoReadException;
import com.farm.doc.exception.CanNoWriteException;
import com.farm.doc.exception.DocNoExistException;
import com.farm.doc.server.FarmDocManagerInter;
import com.farm.doc.server.FarmDocOperateRightInter;
import com.farm.doc.server.FarmDocOperateRightInter.POP_TYPE;
import com.farm.doc.server.FarmDocTypeInter;
import com.farm.doc.server.FarmDocgroupManagerInter;
import com.farm.doc.server.FarmFileManagerInter;
import com.farm.doc.server.commons.DocumentConfig;
import com.farm.doc.server.commons.FarmDocFiles;
import com.farm.doc.util.DocTagUtils;
import com.farm.doc.util.HtmlUtils;
import com.farm.doc.util.LuceneDocUtil;
import com.farm.lucene.FarmLuceneFace;
import com.farm.lucene.server.DocIndexInter;
import com.farm.parameter.FarmParameterService;

/**
 * 文档管理
 * 
 * @author MAC_wd
 */
@Service
public class FarmDocManagerImpl implements FarmDocManagerInter {
	private static final Logger log = Logger.getLogger(FarmDocManagerImpl.class);
	@Resource
	private FarmDocTypeInter farmDocTypeManagerImpl;
	@Resource
	private FarmDocDaoInter farmDocDao;
	@Resource
	private FarmDocfileDaoInter farmDocfileDao;
	@Resource
	private FarmDoctextDaoInter farmDoctextDao;
	@Resource
	private FarmRfDoctextfileDaoInter farmRfDoctextfileDao;
	@Resource
	private FarmRfDoctypeDaoInter farmRfDoctypeDao;
	@Resource
	private FarmDoctypeDaoInter farmDoctypeDao;
	@Resource
	private FarmDocruninfoDaoInter farmDocruninfoDao;
	@Resource
	private FarmDocenjoyDaoInter farmDocenjoyDao;
	@Resource
	private FarmDocOperateRightInter farmDocOperate;
	@Resource
	private FarmDocgroupManagerInter farmDocgroupManagerImpl;
	@Resource
	private FarmDocruninfoDetailDaoInter farmDocruninfoDetailDao;
	@Resource
	private FarmFileManagerInter farmFileServer;
	@Resource
	private FarmtopDaoInter farmtopDaoImpl;

	@Transactional
	public DocEntire createDoc(DocEntire entity, LoginUser user) {
		try {
			{// 保存用量信息
				FarmDocruninfo runinfo = new FarmDocruninfo();
				runinfo.setHotnum(0);
				runinfo.setLastvtime(TimeTool.getTimeDate14());
				runinfo.setPraiseno(0);
				runinfo.setPraiseyes(0);
				runinfo.setVisitnum(0);
				runinfo.setAnsweringnum(0);
				runinfo.setEvaluate(0);
				runinfo = farmDocruninfoDao.insertEntity(runinfo);
				entity.getDoc().setRuninfoid(runinfo.getId());
				entity.setRuninfo(runinfo);
			}
			{// 先保存text
				entity.getTexts().setPstate("1");// 1在用内容。2.版本存档
				entity.getTexts().setPcontent("CREAT");
				entity.setTexts(farmDoctextDao.insertEntity(entity.getTexts()));
				entity.getDoc().setTextid(entity.getTexts().getId());
			}
			{// 保存doc对象
				if (entity.getDoc().getDocdescribe() == null || entity.getDoc().getDocdescribe().trim().length() <= 0) {
					if (entity.getTexts() != null) {
						String html = HtmlUtils.HtmlRemoveTag(entity.getTexts().getText1());
						entity.getDoc().setDocdescribe(html.length() > 128 ? html.substring(0, 128) : html);
					}
				}
				// 生成tags
				if (entity.getDoc().getTagkey() == null || entity.getDoc().getTagkey().trim().length() <= 0) {// 自动生成tag
					entity.getDoc().setTagkey(DocTagUtils.getTags(entity.getTexts().getText1()));
				}
				entity.getDoc().setCtime(TimeTool.getTimeDate14());
				entity.getDoc().setEtime(TimeTool.getTimeDate14());
				entity.getDoc().setCuser(user.getId());
				entity.getDoc().setEuser(user.getId());
				entity.getDoc().setCusername(user.getName());
				entity.getDoc().setEusername(user.getName());
				entity.getDoc().setPubtime(
						entity.getDoc().getPubtime().replaceAll("-", "").replaceAll(":", "").replaceAll(" ", ""));
				if (entity.getDoc().getReadpop() == null) {
					entity.getDoc().setReadpop(POP_TYPE.PUB.getValue());
				}
				if (entity.getDoc().getWritepop() == null) {
					entity.getDoc().setWritepop(POP_TYPE.PUB.getValue());
				}
				if (entity.getDoc().getImgid() != null && !entity.getDoc().getImgid().isEmpty()) {
					farmFileServer.submitFile(entity.getDoc().getImgid());
				}
				if (entity.getDoc().getAuthor() == null || entity.getDoc().getAuthor().isEmpty()) {
					entity.getDoc().setAuthor(user.getName());
				}
				entity.setDoc(farmDocDao.insertEntity(entity.getDoc()));
			}
			{// 保存分类信息
				if (entity.getType() != null) {
					farmRfDoctypeDao.insertEntity(new FarmRfDoctype(entity.getType().getId(), entity.getDoc().getId()));
				}
			}
			entity.setDoc(farmDocDao.insertEntity(entity.getDoc()));
			{
				// 保存关联附件信息（中间表）
				List<String> files = FarmDocFiles.getFilesIdFromHtml(entity.getTexts().getText1());
				for (String id : files) {
					farmRfDoctextfileDao.insertEntity(new FarmRfDoctextfile(entity.getDoc().getId(), id));
					farmFileServer.submitFile(id);
				}
				// 处理文档表单中带人的图片附件
				List<FarmDocfile> files2 = entity.getFiles();
				for (FarmDocfile file : files2) {
					farmRfDoctextfileDao.insertEntity(new FarmRfDoctextfile(entity.getDoc().getId(), file.getId()));
					farmFileServer.submitFile(file.getId());
				}
			}
			// 做索引
			{
				DocIndexInter typeindex = null;
				DocIndexInter groupindex = null;
				try {
					FarmLuceneFace luceneImpl = FarmLuceneFace.inctance();
					if (entity.getDoc().getDomtype().equals("1")) {
						typeindex = luceneImpl.getDocIndex(luceneImpl
								.getIndexPathFile(FarmParameterService.getInstance().getParameter("LUCENE_DIR_KNOW")));
					}
					if (entity.getDoc().getDomtype().equals("3")) {
						typeindex = luceneImpl.getDocIndex(luceneImpl
								.getIndexPathFile(FarmParameterService.getInstance().getParameter("LUCENE_DIR_SITE")));
					}
					if (entity.getDoc().getDomtype().equals("5")) {
						typeindex = luceneImpl.getDocIndex(luceneImpl
								.getIndexPathFile(FarmParameterService.getInstance().getParameter("LUCENE_DIR_FILE")));
					}
					if ("1".equals(entity.getDoc().getState())) {
						if ("1".equals(entity.getDoc().getReadpop())) {
							// 公开权限索引
							typeindex.indexDoc(LuceneDocUtil.getDocMap(entity));
						}
					}
					if (entity.getGroup() != null && !entity.getGroup().getId().isEmpty()) {
						// 创建小组索引
						groupindex = luceneImpl
								.getDocIndex(luceneImpl.getIndexPathFile("GROUP" + entity.getGroup().getId()));
						groupindex.indexDoc(LuceneDocUtil.getDocMap(entity));

					}
				} catch (Exception e) {
					throw new RuntimeException(e);
				} finally {
					try {
						if (groupindex != null) {
							groupindex.close();
						}
						if (typeindex != null) {
							typeindex.close();
						}
					} catch (Exception e1) {
						log.error("lucene error:" + e1);
					}
				}
			}
		} catch (Exception e) {
			throw new RuntimeException("farmDoc文档创建失败：" + e + e.getMessage());
		}
		return entity;
	}

	@Transactional
	public DocEntire editDocByUser(DocEntire entity, String editNote, LoginUser user) throws CanNoWriteException {
		Doc entity2 = farmDocDao.getEntity(entity.getDoc().getId());
		if (!farmDocOperate.isWrite(user, entity2)) {
			throw new CanNoWriteException();
		}
		return editDoc(entity, editNote, user);
	}

	@Transactional
	public DocEntire editDoc(DocEntire entity, String editNote, LoginUser user) {
		DocEntire entity2 = new DocEntire(farmDocDao.getEntity(entity.getDoc().getId()));
		entity2.getDoc().setEtime(TimeTool.getTimeDate14());
		entity2.getDoc().setEuser(user.getId());
		entity2.getDoc().setEusername(user.getName());
		if (entity.getDoc().getPcontent() != null) {
			entity2.getDoc().setPcontent(entity.getDoc().getPcontent());
		}
		if (entity.getDoc().getReadpop() != null) {
			entity2.getDoc().setReadpop(entity.getDoc().getReadpop());
		}
		if (entity.getDoc().getWritepop() != null) {
			entity2.getDoc().setWritepop(entity.getDoc().getWritepop());
		}
		if (entity.getDoc().getState() != null) {
			entity2.getDoc().setState(entity.getDoc().getState());
		}
		if (entity.getDoc().getDocgroupid() != null) {
			entity2.getDoc().setDocgroupid(entity.getDoc().getDocgroupid());
		}
		if (entity.getDoc().getImgid() != null) {
			entity2.getDoc().setImgid(entity.getDoc().getImgid());
		}
		if (entity.getDoc().getTopleve() != null) {
			entity2.getDoc().setTopleve(entity.getDoc().getTopleve());
		}
		if (entity.getDoc().getPubtime() != null) {
			entity2.getDoc().setPubtime(
					entity.getDoc().getPubtime().replaceAll(" ", "").replaceAll("-", "").replaceAll(":", ""));
		}
		if (entity.getDoc().getSource() != null) {
			entity2.getDoc().setSource(entity.getDoc().getSource());
		}
		if (entity.getDoc().getTagkey() != null) {
			entity2.getDoc().setTagkey(entity.getDoc().getTagkey());
		}
		if (entity.getDoc().getShorttitle() != null) {
			entity2.getDoc().setShorttitle(entity.getDoc().getShorttitle());
		}
		if (entity.getDoc().getDomtype() != null) {
			entity2.getDoc().setDomtype(entity.getDoc().getDomtype());
		}
		if (entity2.getDoc().getAuthor()==null) {
			entity2.getDoc().setAuthor(entity2.getDoc().getCusername());
		}
		if (entity.getDoc().getAuthor() != null) {
			entity2.getDoc().setAuthor(entity.getDoc().getAuthor());
		}
		if (entity.getTexts() != null) {
			String html = HtmlUtils.HtmlRemoveTag(entity.getTexts().getText1());
			entity2.getDoc().setDocdescribe(html.length() > 128 ? html.substring(0, 128) : html);
		}
		if (!entity.getDoc().getDocdescribe().isEmpty()) {
			entity2.getDoc().setDocdescribe(entity.getDoc().getDocdescribe());
		}
		if (entity.getDoc().getTitle() != null) {
			entity2.getDoc().setTitle(entity.getDoc().getTitle());
		}
		farmDocDao.editEntity(entity2.getDoc());
		{
			// 直接更新，处理text和版本信息,
			FarmDoctext text = farmDoctextDao.getEntity(entity2.getDoc().getTextid());
			try {
				FarmDoctext histext = (FarmDoctext) BeanUtils.cloneBean(text);
				histext.setId(null);
				histext.setPstate("2");
				histext.setDocid(entity2.getDoc().getId());
				farmDoctextDao.insertEntity(histext);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
			text.setText1(entity.getTexts().getText1());
			text.setCtime(TimeTool.getTimeDate14());
			text.setEtime(TimeTool.getTimeDate14());
			text.setCuser(user.getId());
			text.setPcontent(editNote);
			text.setCusername(user.getName());
			text.setEuser(user.getId());
			text.setEusername(user.getName());
			farmDoctextDao.editEntity(text);
		}
		{
			// 处理超文本中的图片附件
			List<String> files = FarmDocFiles.getFilesIdFromHtml(entity.getTexts().getText1());
			for (String id : files) {
				// 删除掉重复的附件
				List<DBRule> listRules = new ArrayList<DBRule>();
				listRules.add(new DBRule("FILEID", id, "="));
				listRules.add(new DBRule("DOCID", entity2.getDoc().getId(), "="));

				FarmDocfile file = farmFileServer.getFile(id);
				if (file != null) {
					farmRfDoctextfileDao.deleteEntitys(listRules);
					farmRfDoctextfileDao.insertEntity(new FarmRfDoctextfile(entity2.getDoc().getId(), id));
					// 处理附件
					farmFileServer.submitFile(id);
				} else {
					log.error("file(" + id + ") not exist at database!");
				}
			}
			// 处理文档表单中带人的图片附件
			List<FarmDocfile> files2 = entity.getFiles();
			for (FarmDocfile file : files2) {
				farmRfDoctextfileDao.insertEntity(new FarmRfDoctextfile(entity2.getDoc().getId(), file.getId()));
				// 处理附件
				farmFileServer.submitFile(file.getId());
			}
		}

		// 修改分类
		List<FarmRfDoctype> list = farmRfDoctypeDao
				.selectEntitys(new DBRule("DOCID", entity.getDoc().getId(), "=").getDBRules());
		if (list != null && list.size() > 0 && entity.getType() != null) {
			FarmRfDoctype farmRfDoctype = list.get(0);
			farmRfDoctype.setTypeid(entity.getType().getId());
			farmRfDoctypeDao.editEntity(farmRfDoctype);
		}
		// 做索引
		{
			DocIndexInter index = null;
			DocIndexInter groupindex = null;
			try {
				FarmLuceneFace luceneImpl = FarmLuceneFace.inctance();
				if (entity.getDoc().getDomtype().equals("1")) {
					index = luceneImpl.getDocIndex(luceneImpl
							.getIndexPathFile(FarmParameterService.getInstance().getParameter("LUCENE_DIR_KNOW")));
				}
				if (entity.getDoc().getDomtype().equals("3")) {
					index = luceneImpl.getDocIndex(luceneImpl
							.getIndexPathFile(FarmParameterService.getInstance().getParameter("LUCENE_DIR_SITE")));
				}
				if (entity.getDoc().getDomtype().equals("5")) {
					index = luceneImpl.getDocIndex(luceneImpl
							.getIndexPathFile(FarmParameterService.getInstance().getParameter("LUCENE_DIR_FILE")));
				}
				if ("1".equals(entity.getDoc().getReadpop()) && "1".equals(entity.getDoc().getState())) {
					index.deleteFhysicsIndex(entity.getDoc().getId());
					index.indexDoc(LuceneDocUtil.getDocMap(entity));
				}
				if (entity.getGroup() != null && !entity.getGroup().getId().isEmpty()) {
					// 创建小组索引
					groupindex = luceneImpl
							.getDocIndex(luceneImpl.getIndexPathFile("GROUP" + entity.getGroup().getId()));
					groupindex.deleteFhysicsIndex(entity.getDoc().getId());
					groupindex.indexDoc(LuceneDocUtil.getDocMap(entity));
				}
			} catch (Exception e) {
				throw new RuntimeException(e);
			} finally {
				try {
					if (index != null) {
						index.close();
					}
					if (groupindex != null) {
						groupindex.close();
					}
				} catch (Exception e1) {
					log.error("lucene error:" + e1);
				}
			}
		}
		return entity2;
	}

	@Transactional
	public void deleteDoc(String entity, LoginUser user) throws CanNoDeleteException {
		Doc doc = farmDocDao.getEntity(entity);
		if (!farmDocOperate.isDel(user, doc)) {
			throw new CanNoDeleteException("当前用户无此权限！");
		}
		deleteDocNoPop(entity, user);
	}

	@Override
	public DataQuery createSimpleDocQuery(DataQuery query) {
		DataQuery dbQuery = DataQuery.init(query,
				"FARM_DOC  A LEFT JOIN FARM_RF_DOCTYPE B ON B.DOCID =A.ID LEFT JOIN FARM_DOCTYPE C ON C.ID=B.TYPEID LEFT JOIN farm_docgroup d ON d.ID=a.DOCGROUPID",
				"A.ID AS ID,A.DOCDESCRIBE as DOCDESCRIBE,A.WRITEPOP as WRITEPOP,A.READPOP as READPOP,A.TITLE AS TITLE,A.AUTHOR AS AUTHOR,A.PUBTIME AS PUBTIME,A.DOMTYPE AS DOMTYPE,A.SHORTTITLE AS SHORTTITLE,A.TAGKEY AS TAGKEY,A.STATE AS STATE,D.GROUPNAME AS GROUPNAME ");
		return dbQuery;
	}

	@Override
	@Transactional
	public DocEntire getDoc(String docid) {
		if (docid == null || docid.isEmpty()) {
			return null;
		}
		DocEntire doce = new DocEntire(farmDocDao.getEntity(docid));
		doce.setTexts(farmDoctextDao.getEntity(doce.getDoc().getTextid()));
		List<FarmDoctype> types = farmRfDoctypeDao.getDocType(docid);
		if (types.size() > 0) {
			doce.setType(types.get(0));
			doce.setCurrenttypes(farmDocTypeManagerImpl.getTypeAllParent(doce.getType().getId()));
		}
		doce.setRuninfo(farmDocruninfoDao.getEntity(doce.getDoc().getRuninfoid()));
		if (doce.getDoc().getTagkey() != null) {
			String tags = doce.getDoc().getTagkey();
			String[] tags1 = tags.trim().replaceAll("，", ",").replaceAll("、", ",").split(",");
			doce.setTags(Arrays.asList(tags1));
		}
		if (doce.getDoc().getDocgroupid() != null) {
			doce.setGroup(farmDocgroupManagerImpl.getFarmDocgroup(doce.getDoc().getDocgroupid()));
			doce.getGroup().setImgurl(farmFileServer.getFileURL(doce.getGroup().getGroupimg()));
		}
		// 处理附件
		List<FarmDocfile> files = farmDocfileDao.getEntityByDocId(docid);
		for (FarmDocfile file : files) {
			file.setUrl(farmFileServer.getFileURL(file.getId()));
		}
		doce.setFiles(files);
		if (doce.getDoc().getImgid() != null && doce.getDoc().getImgid().trim().length() > 0) {
			String url = DocumentConfig.getString("config.doc.download.url") + doce.getDoc().getImgid();
			doce.setImgUrl(url);
		}
		// 处理作者信息
		{
			User user = new User();
			user.setId(doce.getDoc().getCuser());
			user.setName(doce.getDoc().getCusername());
			doce.setUser(user);
		}
		return doce;
	}

	@Override
	@Transactional
	public DocEntire getDoc(String docid, LoginUser user) throws CanNoReadException, DocNoExistException {
		Doc docbean = farmDocDao.getEntity(docid);
		if (docbean == null) {
			throw new DocNoExistException();
		}
		if (!farmDocOperate.isRead(user, docbean)) {
			throw new CanNoReadException();
		}
		DocEntire doc = getDoc(docid);
		return doc;
	}

	@Override
	@Transactional
	public Doc getDocOnlyBean(String id) {
		return farmDocDao.getEntity(id);
	}

	@Override
	public DataQuery createSimpleTypeQuery(DataQuery query) {
		DataQuery dbQuery = DataQuery.init(query, "farm_doctype a LEFT JOIN farm_doctype b ON a.PARENTID=b.id",
				"a.ID AS id,a.NAME AS NAME,a.TYPEMOD AS TYPEMOD,a.CONTENTMOD AS CONTENTMOD,a.SORT AS SORT,a.TYPE AS TYPE, a.METATITLE AS METATITLE,a.METAKEY AS METAKEY,a.METACONTENT AS METACONTENT,a.LINKURL AS LINKURL,a.PCONTENT AS PCONTENT,a.PSTATE AS PSTATE");
		return dbQuery;
	}

	@Override
	@Transactional
	public void updateDocTypeOnlyOne(String docid, String typeId) {
		List<DBRule> list = new ArrayList<DBRule>();
		list.add(new DBRule("DOCID", docid, "="));
		farmRfDoctypeDao.deleteEntitys(list);
		farmRfDoctypeDao.insertEntity(new FarmRfDoctype(typeId, docid));
	}

	// WHERE PSTATE='2' AND DOCID=''
	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public List<FarmDoctext> getDocVersions(String docId) {
		FarmDoctext docText = farmDoctextDao.getEntity(getDocOnlyBean(docId).getTextid());
		DataQuery dbQuery = DataQuery.getInstance("1", "ID,ETIME,CUSERNAME,DOCID,PCONTENT,PSTATE", "farm_doctext");
		dbQuery.addRule(new DBRule("PSTATE", "1", "!="));
		dbQuery.addRule(new DBRule("DOCID", docId, "="));
		dbQuery.setPagesize(100);
		dbQuery.addSort(new DBSort("CTIME", "DESC"));
		dbQuery.setNoCount();
		@SuppressWarnings("rawtypes")
		List list = new ArrayList();
		list.add(docText);
		try {
			list.addAll(dbQuery.search().getObjectList(FarmDoctext.class));
		} catch (SQLException e) {
			throw new RuntimeException();
		}
		return list;
	}

	@Override
	@Transactional
	public DocEntire getDocVersion(String textId, LoginUser currentUser) {
		if (textId == null) {
			return null;
		}
		FarmDoctext text = farmDoctextDao.getEntity(textId);
		DocEntire doc = new DocEntire(farmDocDao.getEntity(text.getDocid()));
		if (doc.getDoc().getReadpop().equals("0") && !doc.getDoc().getCuser().equals(currentUser.getId())) {
			throw new RuntimeException("没有阅读权限");
		}
		doc.setTexts(text);

		List<FarmDoctype> doctypes = farmRfDoctypeDao.getDocType(doc.getDoc().getId());
		if (doctypes.size() > 0) {
			doc.setType(doctypes.get(0));
			doc.setCurrenttypes(farmDocTypeManagerImpl.getTypeAllParent(doctypes.get(0).getId()));
		}
		if (doc.getDoc().getTagkey() != null) {
			String tags = doc.getDoc().getTagkey();
			String[] tags1 = tags.trim().replaceAll("，", ",").replaceAll("、", ",").split(",");
			doc.setTags(Arrays.asList(tags1));
		}
		return doc;
	}

	@Override
	@Transactional
	public void delImg(String imgid) {
		farmDocfileDao.deleteEntity(farmDocfileDao.getEntity(imgid));
	}

	@Override
	@Transactional
	public void deleteDocNoPop(String entity, LoginUser user) throws CanNoDeleteException {
		Doc doc = farmDocDao.getEntity(entity);
		FarmDoctext text = farmDoctextDao.getEntity(doc.getTextid());
		// 删除置顶
		farmtopDaoImpl.deleteEntitys(new DBRule("docid", entity, "=").getDBRules());
		// 删除收藏
		List<DBRule> joylist = new ArrayList<DBRule>();
		joylist.add(new DBRule("DOCID", doc.getId(), "="));
		farmDocenjoyDao.deleteEntitys(joylist);
		// 删除分类中间表
		List<DBRule> rulesDelType = new ArrayList<DBRule>();
		rulesDelType.add(new DBRule("DOCID", doc.getId(), "="));
		farmRfDoctypeDao.deleteEntitys(rulesDelType);
		// 删除文档
		farmDocDao.deleteEntity(doc);
		// 删除附件中间表
		List<DBRule> rulesDelFile = new ArrayList<DBRule>();
		rulesDelFile.add(new DBRule("DOCID", doc.getId(), "="));
		List<FarmRfDoctextfile> files = farmRfDoctextfileDao.selectEntitys(rulesDelFile);
		for (FarmRfDoctextfile node : files) {
			farmFileServer.delFile(node.getFileid(), user);
		}
		// 删除中间表文档和附件表
		List<DBRule> rulesDelText = new ArrayList<DBRule>();
		rulesDelText.add(new DBRule("DOCID", doc.getId(), "="));
		farmRfDoctextfileDao.deleteEntitys(rulesDelText);
		// 删除附件
		if (doc.getImgid() != null && doc.getImgid().trim().length() > 0) {
			farmDocfileDao.deleteEntity(farmDocfileDao.getEntity(doc.getImgid()));
		}
		// 删除用量明细
		{
			List<DBRule> rulesDelruninfoDetail = new ArrayList<DBRule>();
			rulesDelruninfoDetail.add(new DBRule("RUNINFOID", doc.getRuninfoid(), "="));
			farmDocruninfoDetailDao.deleteEntitys(rulesDelruninfoDetail);
		}
		// 删除用量信息
		farmDocruninfoDao.deleteEntity(farmDocruninfoDao.getEntity(doc.getRuninfoid()));
		// 删除大文本信息
		farmDoctextDao.deleteEntity(text);
		// 做索引
		{
			DocIndexInter index = null;
			DocIndexInter groupindex = null;
			try {
				FarmLuceneFace luceneImpl = FarmLuceneFace.inctance();
				if (doc.getDomtype().equals("1")) {
					index = luceneImpl.getDocIndex(luceneImpl
							.getIndexPathFile(FarmParameterService.getInstance().getParameter("LUCENE_DIR_KNOW")));
				}
				if (doc.getDomtype().equals("3")) {
					index = luceneImpl.getDocIndex(luceneImpl
							.getIndexPathFile(FarmParameterService.getInstance().getParameter("LUCENE_DIR_SITE")));
				}
				if (doc.getDomtype().equals("5")) {
					index = luceneImpl.getDocIndex(luceneImpl
							.getIndexPathFile(FarmParameterService.getInstance().getParameter("LUCENE_DIR_FILE")));
				}
				index.deleteFhysicsIndex(doc.getId());
				if (!doc.getDocgroupid().isEmpty()) {
					// 创建小组索引
					groupindex = luceneImpl.getDocIndex(luceneImpl.getIndexPathFile("GROUP" + doc.getDocgroupid()));
					groupindex.deleteFhysicsIndex(doc.getDocgroupid());
				}
			} catch (Exception e) {
				throw new RuntimeException(e);
			} finally {
				try {
					if (groupindex != null) {
						groupindex.close();
					}
					if (index != null) {
						index.close();
					}
				} catch (Exception e1) {
					log.error("lucene error:" + e1);
				}
			}
		}
	}
}
